package cn.tedu._05mvcboot06.controller;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import cn.tedu._05mvcboot06.common.response.JsonResult;
import cn.tedu._05mvcboot06.common.response.StatusCode;
import cn.tedu._05mvcboot06.mapper.UserMapper;
import cn.tedu._05mvcboot06.pojo.dto.UserArticleDTO;
import cn.tedu._05mvcboot06.pojo.dto.UserLoginDTO;
import cn.tedu._05mvcboot06.pojo.entity.Article;
import cn.tedu._05mvcboot06.pojo.vo.ArticleVO;
import cn.tedu._05mvcboot06.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.jws.soap.SOAPBinding;
import javax.servlet.http.HttpSession;
@Validated
@Api(tags = "用户模块")
@RestController
@RequestMapping("/v1/users/")
public class UserController {

    @Autowired
    private UserMapper usermapper;

    @ApiOperation(value = "登录功能")
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        String username =userLoginDTO.getUsername();
        String password=userLoginDTO.getPassword();

        UserVO userVO = usermapper.selectUser(username,password);

        if (userVO==null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        session.setAttribute("user",userVO);
        return JsonResult.ok();
        }



        @ApiOperation("发表文章功")
        @PostMapping("article")
    public JsonResult insert(@RequestBody @Validated UserArticleDTO userArticleDTO,@ApiIgnore HttpSession session){
        UserVO userVO = (UserVO) session.getAttribute("user");

//        if (userVO==null){
//            return new JsonResult(StatusCode.NOT_LOGIN);
//        }
            Article article = new Article();
            BeanUtils.copyProperties(userArticleDTO,article);
            article.setUserId(userVO.getId());
            usermapper.insert(article);
            return JsonResult.ok();
        }

        @ApiOperation("查询指定文章功能")
    @GetMapping("selectByArticleId")
        @ApiImplicitParam(name = "id",value = "用户编号",required = true,dataType =  "int")
    public JsonResult selectByArticleId(@Range(min = 1,max = 100,message = "Id在1-100之间") @RequestParam int id){
       ArticleVO articleVO = usermapper.selectByArticleId(id);

        return JsonResult.ok(articleVO);
        }

}
